// pages/optional/school/index.js
const {
  schoolList,
  schoolAdd,
  majorPageList
} = require('../../../api/api')
const {
  checkLogin,
  filterObj,
  throttle,
  returnLabel
} = require('../../../utils/util')
const selectorRouteDatas = [{
    id: 0,
    title: "全国",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "专业",
    type: "checkbox",
    key: "major",
    items: []
  },
  {
    id: 3,
    title: "排序",
    key: "orderBy",
    type: 'radiobox',
    items: [{
        id: 0,
        title: "默认排序",
        checked: true
      }, {
        id: 'scoreDesc',
        title: "分数由高到低",
      },
      {
        id: 'scoreAsc',
        title: "分数由低到高",
      },
      {
        id: 'hotDesc',
        title: "热度由高到低",
      },
      {
        id: 'workRateDesc',
        title: "就业率由高到低",
      },
      {
        id: 'upRateDesc',
        title: "国内升学率由高到底",
      },
    ],
  },
  {
    id: 4,
    title: "其他",
    key: "batch",
    type: 'other',
    items: [],
  },


]
const filterBatch = [{
    id: 3,
    title: "办学层次",
    key: "eduLevelName",
    type: 'radiobox',
    items: [{
        id: '本科',
        title: "本科",
        checked: true
      }, {
        id: '专科（高职）',
        title: "专科（高职）",
      },

    ],
  },
  {
    id: 3,
    title: "办学类型",
    key: "eduType",
    type: 'checkbox',
    items: [{
        id: '公办学校',
        title: "公办学校",
        checked: true
      }, {
        id: '民办学校',
        title: "民办学校",
      },
      {
        id: '中外合作办学',
        title: "中外合作办学",
      },
      {
        id: '内地港澳台合作办学',
        title: "内地港澳台合作办学",
      },
    ],
  },
  {
    id: 3,
    title: "院校特色",
    key: "schoolLabel",
    type: 'checkbox',
    items: [{
        id: 985,
        title: "985",
      }, {
        id: 211,
        title: "211",
      },
      {
        id: '双一流',
        title: "双一流",
      },
      {
        id: '强基计划',
        title: "强基计划",
      },
    ],
  },
  {
    id: 4,
    title: "院校类型",
    key: "schoolType",
    type: 'checkbox',
    items: [{
        id: '综合类',
        title: "综合类",
      }, {
        id: '理工类',
        title: "理工类",
      },
      {
        id: '农林类',
        title: "农林类",
      },
      {
        id: '医药类',
        title: "医药类",
      },
      {
        id: '师范类',
        title: "师范类",
      },
    ],
  },
]
const optionalRouteDatas = [{
    id: 0,
    title: "全国",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "年份",
    type: "radiobox",
    key: "year",
    items: [
      {
        id: '2024',
        title: '2024'
      },
    ]
  },


]

function filterArr(selected, selectData) {
  let c = selectData.filter((item) => {
    return (selected.indexOf(item.id) > -1)
  })
  return c
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    list: [],
    currentRegion: {
      name: '全国',
      code: 0
    },
    filterBatch: filterBatch,
    selectedData: {
      province: 0,
      batch: 1,
      major: [],
      orderBy: 0,
      eduLevelName: 0,
      eduType: [],
      schoolLabel: [],
      schoolType: [],
      selectedMajorList:[]
    },
    selectorDataList: selectorRouteDatas,
    optionalFilterRouteKey: 'optionalChooseFilters',
    optionalData: {
      province: 0,
      year: '2024'
    },
    optionalDataList: optionalRouteDatas,
    showSelect: false,
    type: {
      name: '本科',
      id: 2,
    },
    pageNo: 1,
    loginVisible: true,
    pageSize: 20,
    pageTNo: 1,
    pageTSize: 20,
    filterRouteKey: "optionalSchoolFilters",
    selectedMajorList: [],
    bottomLift: getApp().globalData.bottomLift,
    key: 'add',
    setting: {
      width: '220rpx',
      weight: 'normal',
      color: '#808080',
      fontSize: '26rpx',
      top: '112rpx',
      height: '50rpx',
      padding: '0'
    },
    selectSetting: {
      top: '80rpx'
    },
    selectedIds: [],
    selectedList: [],
    planMatchId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      this.setData({
        ...params
      })
    }
    const {
      filterRouteKey,
      selectedData,
      optionalDataList,
      optionalFilterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, selectedData)
    var d=new Date()
    var year=d.getFullYear()
    var month=d.getMonth()
    if(month>6){
      year=year+1
    }
    var len=year+1
    var yearList=[]
    for(var i=year;i<len;i++){
      yearList.push({id:i,title:i})
    }
    optionalDataList[1].items=yearList
    this.setData({
      optionalDataList
    })
    if (!wx.getStorageSync(optionalFilterRouteKey)) {
      let obj = {
        province: wx.getStorageSync('optionalFilters').province,
        year: year
      }
      this.setData({
        optionalData: obj
      })
      wx.setStorageSync(optionalFilterRouteKey, obj)
    } else {
      this.setData({
        optionalData: wx.getStorageSync(optionalFilterRouteKey)
      })
    }

    this.fetchCity()
    this.getMajorPageList()
  },
  async fetchCity() {
    const {
      filterBatch,
      selectorDataList,
      optionalDataList
    } = this.data
    const eduTypeList = wx.getStorageSync('edu_type') || await getApp().getDictData('edu_type')
    const schoolLabelList = wx.getStorageSync('school_label') || await getApp().getDictData('school_label')
    const schoolTypeList = wx.getStorageSync('school_type') || await getApp().getDictData('school_type')
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    cityList.unshift({
      id: 0,
      title: '全国',
      checked: true
    })
    selectorDataList[0].items = cityList
    optionalDataList[0].items = cityList
    filterBatch[2].items = schoolLabelList
    filterBatch[1].items = eduTypeList
    filterBatch[3].items = schoolTypeList
    this.setData({
      filterBatch,
      selectorDataList,
      optionalDataList
    })
    this.filterKeyFunc('optionalData', 'optionalDataList', 'optionalChooseFilters')
    this.filterKeyFunc('selectedData', 'selectorDataList', 'optionalSchoolFilters')
  },

  filterKeyFunc(selectedKey, listKey, filterRouteKey) {
    const selectedData = wx.getStorageSync(filterRouteKey)
    const selectorDataList = this.data[listKey]
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = (item.key == 'province' || item.key == 'year') ? c.length > 0 ? c[0].title : item.title : item.title
    })
    this.setData({
      [listKey]: selectorDataList,
      [selectedKey]: selectedData
    })
    if (listKey == 'selectorDataList') {
      this.filterMajor()
    }
  },

  //修改专业--执行onloadFunc
  filterMajor() {
    const {
      selectorDataList,
      filterRouteKey
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)

    const selectorMajorList = selectorDataList[1].items
    const selectedMajorList = filterArr(selectedData['major'], selectorMajorList)
    this.setData({
      selectedMajorList
    })
    checkLogin().then((res) => {
      this.onLoadFunc()
    })
  },
  // clear() {
  //   const {
  //     filterRouteKey
  //   } = this.data
  //   const selectedData = wx.getStorageSync(filterRouteKey)
  //   selectedData.major = []
  //   selectedData.selectedMajorList = []
  //   wx.setStorageSync(filterRouteKey, selectedData)
  //   this.setData({
  //     selectedData,
  //     selectedMajorList: []
  //   })
  //   this.filterMajor()
  // },
  // clearItem(e) {
  //   const {
  //     filterRouteKey,
  //     selectedMajorList
  //   } = this.data

  //   let {
  //     id
  //   } = e.currentTarget.dataset
  //   var selectedData = wx.getStorageSync(filterRouteKey)
  //   const newList = selectedMajorList.filter((item) => {
  //     return item.id !== id
  //   })
  //   let major = selectedData.major
  //   major.splice(major.indexOf(id), 1)
  //   selectedData.selectedMajorList=newList
  //   wx.setStorageSync(filterRouteKey, selectedData)
  //   this.setData({
  //     selectedData,
  //     selectedMajorList: newList
  //   })
  //   this.filterMajor()
  // },
  deleteItem(e) {
    const {
      id,
      list
    } = e.detail
    const {
      selectedList,
      selectedIds
    } = this.data
    selectedList.map((item, index) => {
      if (item.id == id) {
        selectedList.splice(index, 1)
      }
    })
    selectedIds.splice(selectedIds.indexOf(e.detail, 1))
    this.setData({
      selectedList,
      selectedIds,
      list
    })
  },
  addItem(e) {
    const {
      selectedIds,
      selectedList
    } = this.data
    const {
      list,
      value
    } = e.detail
    selectedList.push({
      id:value.id,
      title:value.name
    })
    selectedIds.push(value.id)
    this.setData({
      selectedIds,
      selectedList,
      list
    })
  },

  async onSelectChangedRoute(e) {
    const {
      filterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, {
      ...e.detail
    });
    this.filterKeyFunc('selectedData', 'selectorDataList', 'optionalSchoolFilters')
  },
  async onSelectChangedRoute1(e) {
    const {
      optionalFilterRouteKey
    } = this.data
    wx.setStorageSync(optionalFilterRouteKey, {
      ...e.detail
    });
    this.filterKeyFunc('optionalData', 'optionalDataList', 'optionalChooseFilters')
  },
  //意向学校改变
  onSelectChange(e) {
    const {
      selectedList,
      selectedIds
    } = e.detail
    const {
      list
    } = this.data
    if (e.detail.id) {
      list.map((item) => {
        item.map((child) => {
          if (child.id == e.detail.id) {
            child.isCompare = false
          }
        })
      })
    } else {
      list.map((item) => {
        item.map((child) => {
          child.isCompare = false
        })
      })
    }
    this.setData({
      list,
      selectedList,
      selectedIds
    })
    // console.log(list, selectedList, selectedIds)
  },
  scroll() {
    const {
      selectorDataList,
      pageTSize
    } = this.data
    const count = selectorDataList[1].items.length - 1
    if (selectorDataList[1].items[count].length < pageTSize) {
      return
    }

    this.getMajorPageList(true)
  },
  searchMaj(e) {
    const {
      name
    } = e.detail
    const {
      selectorDataList
    } = this.data
    selectorDataList[1].items = []
    this.setData({
      name,
      pageTNo: 1,
      selectorDataList
    })
    this.getMajorPageList(true)
  },
  async getMajorPageList(flag) {
    const {
      pageTNo,
      pageTSize,
      name,
      selectorDataList,
    } = this.data
    let params = {
      name,
      pageNo: pageTNo,
      pageSize: pageTSize,
    }
    params = filterObj(params)
    const {
      result
    } = await majorPageList(params)
    result.records = result.records.map(e => {
      return {
        id: e.specialId,
        title: e.name,
        desc: e.level1Name + '-' + e.level2Name + '-' + e.level3Name,
      }
    })
    selectorDataList[1].items = selectorDataList[1].items.concat(result.records)
    if (result.records.length == 0) {
      return
    }
    this.setData({
      selectorDataList,
      pageTNo: pageTNo + 1,
    })
    if(flag!==undefined){
      this.selectComponent("#selector").syncData1(selectorDataList);
    }

  },
  onLoadFunc() {
    this.setData({
      pageNo: 1,
      list: []
    })
    this.getList()
  },
  async getList() {
    this.setData({
      loader: true
    })
    const {
      type,
      pageNo,
      pageSize,
      filterRouteKey,
      selectedIds
    } = this.data
    let {
      province,
      major,
      orderBy,
      eduLevelName,
      schoolLabel,
      eduType,
      schoolType
    } = wx.getStorageSync(filterRouteKey)
    eduType = eduType.join(',')
    schoolType = schoolType.join(',')
    let params = {
      pageNo,
      pageSize,
      provincesCode: province,
      specialtyIds: major,
      orderBy,
      eduLevelName,
      schoolType,
      eduType
    }
    let obj = wx.getStorageSync('school_label_obj')
    let newObj = {}
    schoolLabel.map(e => {
      if (obj[e]) {
        newObj[obj[e]] = 1
      }
    })
    params = Object.assign(newObj, params)
    params = filterObj(params)
    // console.log(params)
    const {
      result
    } = await schoolList(params)
    if (result.records.length == 0) {
      this.setData({
        loader: false
      })
      return
    }
    result.records.map((item) => {
      item['filter'] = returnLabel(item)
      if(selectedIds.indexOf(item.id)>-1){
        item.isCompare=true
      }
    })

    this.setData({
      ['list[' + (pageNo - 1) + ']']: result.records,
      pageNo: pageNo + 1,
      loader: false
    })
  },
  confirm(e) {
    const {
      selectedList,
      selectedIds
    } = this.data
    const params = {
      selectedList,
      mode,
      selectedIds
    }
    wx.navigateTo({
      url: '/pages/optional/report/index?params=' + encodeURIComponent(JSON.stringify(params))
    })
  },
  onReachBottom() {
    const {
      list,
      pageSize
    } = this.data
    const count = list.length - 1
    console.log(count)
    if (list[count].length < pageSize) {
      return
    }
    this.getList()
  },

  goto(e) {
    const {
      url,
    } = e.currentTarget.dataset
    wx.navigateTo({
      url
    })
  },
  search() {
    checkLogin().then((res) => {
      wx.navigateTo({
        url: '/pages/search/index?type=school',
      })
    }).catch((e) => {
      this.setData({
        loginVisible: false,
        list: []
      })
    })

  },
  toggleModal() {
    this.setData({
      visible: !this.data.visible
    })
  },

  clearIds() {
    this.setData({
      selectedIds: [],
      selectedList: []
    })
  },
  onShareAppMessage() {
    return {
      title: '院校选科',
      imageUrl:'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})